#!/usr/bin/python2.4


class TotalCount(object):

  __slots__ = 'total', 'count'

  def __init__(self, total=0, count=0):
    self.set(total, count)

  def __repr__(self):
    return '%s(total=%r, count=%r)' % (type(self).__name__,
                                       self.total,
                                       self.count)

  def set(self, total, count):
    self.total = total
    self.count = count

  def add(self, num, inc=1):
    self.total += num
    self.count += inc

  def get(self):
    return self.total, self.count

  def pformat(self):
    if isinstance(self.total, float):
      str_total = '%.1f' % self.total
    else:
      str_total = '%s' % self.total
    return '%sh: %s' % (str_total, self.count)


class TestStats(object):

  __slots__ = 'name', 'total_count', 'runs', 'data'

  def __init__(self, name, total_count=None):
    self.name = name
    if total_count is None:
      total_count = TotalCount()
    self.total_count = total_count
    self.runs = []
    self.data = {}

  def __repr__(self):
    return '%s(%s)' % (type(self).__name__, self.pformat())

  def __getitem__(self, key):
    return self.data[key][1]

  def clear(self):
    self.data.clear()

  def get(self, status):
    return self.data.get(status, (TotalCount(), []))

  def status_pformat(self, status):
    if status:
      stats = self.get(status)[0]
      if self.total_count.total:
        percentage = '%.1f%%' % (stats.total * 100. / self.total_count.total)
      else:
        percentage = 'nan'
      return '%s (%s)' % (percentage, stats.pformat())
    else:
      return '%s (%s)' % (self.name, self.total_count.pformat())

  def add(self, status, num, inc=1, add_to_total=True, run=None):
    status_total_count, status_runs = self.data.get(status, (None, None))
    if status_total_count is None:
      status_total_count, status_runs = self.data[status] = TotalCount(), []
    status_total_count.add(num, inc)
    if run:
      status_runs.append(run)
      self.runs.append(run)
    if add_to_total:
      self.total_count.add(num, inc)

  def pformat(self):
    results = []
    for status in sorted(self.data.iterkeys()):
      results.append('%s: %s' % (status, self.status_pformat(status)))
    return '%s - %s' % (self.status_pformat(None), ', '.join(results))
